﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using VPLink2013.Framework;
using VPLink2013.Framework.Extensions;
using Microsoft.SharePoint.Utilities;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace VPLink2014
{
    public partial class Widget : LayoutsPageBase
    {
        private ConfigWidget config = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            string pathToWidget = SPUtility.GetVersionedGenericSetupPath(@"\TEMPLATE\LAYOUTS\VPLink2014\Widgets\Config", 15);
            string fileName = string.Format(@"{0}\widget.config.xml", pathToWidget);
            config = FileSerialization.CreateObjFromXML<ConfigWidget>(fileName);

            string cachePath = SPUtility.GetVersionedGenericSetupPath(@"\TEMPLATE\LAYOUTS\VPLink2014\Widgets\Cache", 15);
            string rerDCacheFile = "rerDcache.xml";
            string rerBCacheFile = "rerBcache.xml";
            string meteoCacheFile = "meteocache.xml";
            string responseJson = "{}";
            string param = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(this.Request.QueryString["widget"]))
                {
                    if (this.Request.QueryString["widget"] == "meteo")
                    {
                        string wsMeteoUrl = string.Format(@"{0}?lat={1}&lon={2}&lang={3}&units={4}&mode={5}",
                            config.WebServices.meteo.url,
                            config.WebServices.meteo.latitude,
                            config.WebServices.meteo.longitude,
                            config.WebServices.meteo.langue,
                            config.WebServices.meteo.unite,
                            config.WebServices.meteo.mode);
                        if (FileSerialization.CheckFileCacheExists(string.Format(@"{0}\{1}", cachePath, meteoCacheFile), config.CacheExpiration.WidgetMeteo))
                        {
                            responseJson = FileSerialization.CreateObjFromXML<MeteoInfo>(string.Format(@"{0}\{1}", cachePath, meteoCacheFile)).ToJson();
                        }
                        else
                        {
                            responseJson = GetMeteoInfoToCache(wsMeteoUrl, string.Format(@"{0}\{1}", cachePath, meteoCacheFile), config.CacheExpiration.WidgetMeteo);
                        }
                    }
                    else
                    {
                        if (this.Request.QueryString["widget"] == "rer")
                        {
                            if (!string.IsNullOrEmpty(this.Request.QueryString["nom"]))
                            {
                                if (this.Request.QueryString["nom"] == "D")
                                {
                                    if (FileSerialization.CheckFileCacheExists(string.Format(@"{0}\{1}", cachePath, rerDCacheFile), config.CacheExpiration.WidgetRer))
                                    {
                                        responseJson = FileSerialization.CreateObjFromXML<RerWidget>(string.Format(@"{0}\{1}", cachePath, rerDCacheFile)).ToJson();
                                    }
                                    else
                                    {
                                        responseJson = GetRerInfoToCache(config.WebServices.rerD.url,
                                            config.WebServices.rerD.xpath,
                                            string.Format(@"{0}\{1}", cachePath, rerDCacheFile),
                                            config.CacheExpiration.WidgetRer);
                                    }
                                    // recherche cache
                                    #region cache asp
                                    //System.Object cachedObject = Cache[rerDcacheKey];
                                    //if( cachedObject != null )
                                    //{
                                    //    responseJson = cachedObject.ToString();
                                    //}
                                    //else
                                    //{
                                    //    responseJson = GetRerInfoToCache( config.WebServices.rerD.url, 
                                    //        config.WebServices.rerB.xpath, 
                                    //        rerDcacheKey, 
                                    //        config.CacheExpiration.WidgetRer );
                                    //}
                                    #endregion
                                }
                                if (this.Request.QueryString["nom"] == "B")
                                {
                                    if (FileSerialization.CheckFileCacheExists(string.Format(@"{0}\{1}", cachePath, rerBCacheFile), config.CacheExpiration.WidgetRer))
                                    {
                                        responseJson = FileSerialization.CreateObjFromXML<RerWidget>(string.Format(@"{0}\{1}", cachePath, rerBCacheFile)).ToJson();
                                    }
                                    else
                                    {
                                        responseJson = GetRerInfoToCache(config.WebServices.rerB.url,
                                            config.WebServices.rerB.xpath,
                                            string.Format(@"{0}\{1}", cachePath, rerBCacheFile),
                                            config.CacheExpiration.WidgetRer);
                                    }
                                    // recherche cache
                                    #region cache ASP
                                    //System.Object cachedObject = Cache[rerBcacheKey];
                                    //if( cachedObject != null )
                                    //{
                                    //    responseJson = cachedObject.ToString();
                                    //}
                                    //else
                                    //{
                                    //    responseJson = GetRerInfoToCache( config.WebServices.rerB.url, config.WebServices.rerB.xpath, rerBcacheKey, config.CacheExpiration.WidgetRer );
                                    //}
                                    #endregion
                                }
                            }
                        }
                    }
                }
                Response.Write(responseJson);
                Response.End();
            }
            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                responseJson = string.Format(@"{{""messageError"" : ""{0}"", ""stackTrace"" : ""{1}""}}", ex.Message.ToJson(), ex.StackTrace.ToJson());
                Response.Write(responseJson);
                Response.End();
            }
        }

        private string GetMeteoInfoToCache(string wsUrl, string cacheFilePath, int expirationTime)
        {
            string responseJson = "{}";
            MeteoInfo meteoInfo = null;
            if (bool.Parse(config.ConnectionConfig.IsProxy))
            {
                meteoInfo = WidgetOperations.GetMeteoInfoByUrl(wsUrl,
                    config.ConnectionConfig.proxyAddress,
                    config.ConnectionConfig.login,
                    config.ConnectionConfig.pwd,
                    config.ConnectionConfig.domain);
            }
            else
            {
                meteoInfo = WidgetOperations.GetMeteoInfoByUrl(wsUrl);
            }
            responseJson = meteoInfo.ToJson();
            FileSerialization.CreateXmlFromObj(meteoInfo, cacheFilePath);
            return responseJson;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="wsUrl"></param>
        /// <param name="rerBcacheKey"></param>
        /// <param name="responseJson"></param>
        /// <param name="expirationTime">in minutes</param>
        /// <returns></returns>
        private string GetRerInfoToCache(string wsUrl, string xpath, string cacheFilePath, int expirationTime)
        {
            string responseJson = "{}";
            List<RerInfo> rerInfo = null;
            RerAlert alert = null;
            if (bool.Parse(config.ConnectionConfig.IsProxy))
            {
                rerInfo = WidgetOperations.GetRerInfoByUrl(wsUrl, xpath,
                    config.ConnectionConfig.proxyAddress,
                    config.ConnectionConfig.login,
                    config.ConnectionConfig.pwd,
                    config.ConnectionConfig.domain);
                alert = WidgetOperations.GetRerExtraInfo(config.WebServices.alertInfo.xpathInfo,
                    config.WebServices.alertInfo.xpathDetailInfo,
                    config.WebServices.alertInfo.url,
                    wsUrl,
                    config.ConnectionConfig.proxyAddress,
                    config.ConnectionConfig.login,
                    config.ConnectionConfig.pwd,
                    config.ConnectionConfig.domain);
            }
            else
            {
                rerInfo = WidgetOperations.GetRerInfoByUrl(wsUrl, xpath);
                alert = WidgetOperations.GetRerExtraInfo(config.WebServices.alertInfo.xpathInfo,
                    config.WebServices.alertInfo.xpathDetailInfo,
                    config.WebServices.alertInfo.url, wsUrl);
            }
            if (rerInfo.Count == 0)
            {
                responseJson = string.Format(@"{{""messageError"" : ""Le site transilien rencontre des problèmes actuellement""}}");
            }
            else
            {
                responseJson = string.Format(@"{{""list"":{0},""alert"":{1}}}", rerInfo.ToJson(), alert.ToJson());
                #region Cache server
                FileSerialization.CreateXmlFromObj(new RerWidget() { rerInfoList = rerInfo, alert = alert }, cacheFilePath);
                #endregion
            }
            // insertion cache
            #region Cache ASP
            //Cache.Insert( cacheKey, responseJson, null,
            //    System.Web.Caching.Cache.NoAbsoluteExpiration,
            //    TimeSpan.FromMinutes( expirationTime ) );
            #endregion

            return responseJson;
        }
    }
}
